using System;
using System.Collections.Generic;
using Sirenix.OdinInspector;
using Sirenix.Utilities;
using UnityEngine;
using YDExtendTool.Scripts;

namespace DDA
{
    public class DDAParser : Singleton<DDAParser>
    {
        [ShowInInspector] public DynamicDifficultAdjustTree DDAResourceLoadTree;
        [ShowInInspector] private List<DynamicDifficultAdjustTree> _aliveTreeList = new();
        #if UNITY_EDITOR
        [ShowInInspector, LabelText("测试用DDA树")]
        public DynamicDifficultAdjustTree testTree;
        #endif

        private void Awake()
        {
            _aliveTreeList.Clear();
        }

        public void AddTree(DynamicDifficultAdjustTree tree)
        {

            if (tree.RootNode is DDAStart start)
            {
                start.Reset();
                _aliveTreeList.Add(tree);
            }
            else
            {
                Debug.LogWarning($"DDA 根节点不存在或者根节点不为Start:{tree.name}");
            }
        }

        public void RemoveTree(DynamicDifficultAdjustTree tree)
        {
            if (tree == null) return;

            for (int i = 0; i < _aliveTreeList.Count; i++)
            {
                if (_aliveTreeList[i] == tree)
                {
                    Debug.Log(tree.name);
                }
            }

            _aliveTreeList.Remove(tree);
            if (_aliveTreeList.Count ==0) LoadTree();
        }

        [Button]
        public void LoadTree()
        {
            if (DDAResourceLoadTree.RootNode is DDATreeNodeBase root)
            {
                root.Reset();
                if (root.Invoke())
                {
                    Debug.Log("所有DDATree资源已经加载完成");
                }
            }
        }
        
        [Button("测试树逐步执行")]
        public void Step()
        {
            if (testTree.RootNode is DDAStart start)
            {
                if (start.Invoke())
                {
                    Debug.Log("当前DDA树已经执行完成");
                }
            }
        }
        
        [Button("测试树重置")]
        public void ResetTestTree()
        {
            if (testTree.RootNode is DDAStart start)
            {
                start.Reset();
            }
            _aliveTreeList.Clear();
        }

        [Button("重置")]
        public void Reset()
        {
            if (DDAResourceLoadTree.RootNode is DDAStart start)
            {
                start.Reset();
            }
            _aliveTreeList.Clear();
        }

        [Button("暂停")]
        public void Stop()
        {
            Reset();
            StopAllCoroutines();
        }
        
        private void OnDestroy()
        {
            Reset();
        }
    }
}
